use std::fs::{File, OpenOptions};
use std::{fs, io};
use std::io::{BufRead, Read, Write};
use std::path::Path;
use std::sync::Arc;
use dashmap::DashMap;
use tokio::io::AsyncWriteExt;
use crate::{CmdCache, parse_cmd, Redis, Session};

#[derive(Clone, Debug)]
pub enum AofType {
    Always, // 每个命令写入一次
    EverySec, // 每一秒写入一次
}

pub fn write_aof_always(aof_path: String, cmd: String) {
    let cmd = cmd.replace("\r\n", "\t");

    let path = Path::new(aof_path.as_str());

    if !path.exists() {
        File::create(path);
    }
    let mut file = OpenOptions::new().
        append(true)
        .create(true)
        .open(aof_path.as_str()).unwrap();

    write!(file, "{}", format!("{}\r\n", cmd));
}


pub fn write_aof_every_sec(aof_path: String, cmd_cache: CmdCache) {
    for cmd in cmd_cache.data.read().unwrap().iter() {
        write_aof_always(aof_path.clone(), (*cmd).clone());
    }

    // 清空缓存
    cmd_cache.data.write().unwrap().clear();
}


pub fn load_aof(aof_path: String, db: Redis, sesseion_id: String, sessions: Arc<DashMap<String, Session>>) -> Result<(), Box<dyn std::error::Error>> {
    let path = Path::new(aof_path.as_str());

    if !path.exists() {
        return Ok(());
    }


    let mut file = File::open(aof_path.clone()).unwrap();
    // file.read_to_string();

    for line in io::BufReader::new(file).lines() {
        println!("{:?}", line);

        let msg = line.unwrap().replace("\t", "\r\n");

        parse_cmd(msg, db.clone(), sesseion_id.clone(), sessions.clone())?;
    }

    // fs::remove_file(aof_path)?;
    Ok(())
}


